package com.qjz.diancan.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {

    @Value("${upload.dir}")
    private String uploadDir;

    @PostMapping("/file/upload")
    public ResponseEntity<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file)
    {
        if (file.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        try {
            // 获取资源目录的绝对路径
            String resourceDirectory = new File(uploadDir).getAbsolutePath();
            File directory = new File(resourceDirectory);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 使用 UUID 生成唯一的文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(resourceDirectory, fileName);
            // 保存文件
            Files.write(filePath, file.getBytes());
            // 返回文件路径作为响应
            Map<String, String> response = new HashMap<>();
            response.put("data", "/uploads/" + fileName);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
